package com.example.lab1;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;


public class ClientThread extends Thread {

	/*
	 * Идентификатор клиента
	 */
	int mClientId;

	/*
	 * Входной поток сокета
	 */
	BufferedReader mIn;

	/*
	 * Выходной поток сокета
	 */
	PrintWriter mOut;

	/*
	 * Сокет клиента
	 */
	Socket mSocket;

	/*
	 * Адрес сокета
	 */
	InetSocketAddress mInetSocketAddress;

	/*
	 * Сообщение приветствия
	 */
	private final String mHelloMessage;

	/*
	 * Команда для подсчета кв. корня
	 */
	private final String mCommand;

	/*
	 * Сообщение для прекращения обмена данными
	 */
	private final String mShutdownMessage = "shutdown";

	/*
	 * Конструктор
	 */
	public ClientThread(InetSocketAddress inetSocketAddress, int id, String helloMessage, String commandMessage) {
		mInetSocketAddress = inetSocketAddress;
		mClientId = id;
		mHelloMessage = helloMessage;
		mCommand = commandMessage;

		start();
	}

	/*
	 * Действия треда
	 */
	public void run() {
		String fromServerMessage = "";
		String fromClientMessage = mHelloMessage + " " + mClientId;

		try {
			mSocket = new Socket(mInetSocketAddress.getAddress(), mInetSocketAddress.getPort());
			mOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(mSocket.getOutputStream())), true);
			mIn = new BufferedReader(new InputStreamReader(mSocket.getInputStream()));
		}
		catch (IOException e) {
			e.printStackTrace();
		}

		//Log.d(MainActivity.APP_TAG, "FROM CLIENT MESSAGE: " + fromClientMessage);
		writeToLog("FROM CLIENT MESSAGE: " + fromClientMessage);
		mOut.println(fromClientMessage);

		try {
			fromServerMessage = mIn.readLine();
			//Log.d(MainActivity.APP_TAG, "FROM SERVER MESSAGE: " + fromServerMessage);
			writeToLog("FROM SERVER MESSAGE: " + fromServerMessage);

			try {
				sleep(5000);
			}
			catch (InterruptedException e) {
				e.printStackTrace();
			}

			// Посыл команд
			mOut.println(mCommand);
			//Log.d(MainActivity.APP_TAG, "COMMAND MESSAGE: " + mCommand);
			writeToLog("COMMAND MESSAGE: " + mCommand);

			fromServerMessage = mIn.readLine();
			//Log.d(MainActivity.APP_TAG, "FROM SERVER MESSAGE: " + fromServerMessage);
			writeToLog("FROM SERVER MESSAGE: " + fromServerMessage);

			// Завершить работу серверного треда
			mOut.println(mShutdownMessage);

			// Вывести подтверждение
			fromServerMessage = mIn.readLine();
			//Log.d(MainActivity.APP_TAG, "FROM SERVER MESSAGE: " + fromServerMessage);
			writeToLog("FROM SERVER MESSAGE: " + fromServerMessage);
		}
		catch (IOException e) {
			System.err.println("IO Exception");
			e.printStackTrace();
		}
		finally {
			// всегда закрывать сокет
			try {
				mSocket.close();
			}
			catch (IOException e) {
				System.err.println("Socket is not closed");
			}
		}
	}

	void writeToLog(final String logString) {
		MainActivity.mActivity.runOnUiThread(new Runnable() {
			public void run() {
				MainActivity.mLog.append(logString + "\n");
			}
		});
	}

}